/**
 * Copyright (c) 2024,  科泰集团教研团队
 * 版权所有，请勿侵权
 */
package com.ktjiaoyu.controller;

import com.ktjiaoyu.entity.SysUser;
import com.ktjiaoyu.ex.LoginException;
import com.ktjiaoyu.service.SysUserService;
import com.ktjiaoyu.utils.Constants;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;


/**
 * @author 科泰集团教研团队
 * @version 1.0.0
 * @packageName com.ktjiaoyu.controller
 * @fileName LoginController.java
 * @createTime 2024/10/15 17:26
 * @lastModify 2024/10/15 17:26
 */
@Controller
public class LoginController extends BaseController{
    @Autowired
    private SysUserService sysUserService;

    @GetMapping("/login")
    public String toLogin(){
        // 由于login.jsp页面不在WEB-INF下，所以不能返回逻辑视图名称
        // 需要使用forward:前缀告知SpringMVC转发到根路径下的login.jsp
        return forward("/login.jsp");
    }

    @PostMapping("/login")
    public String login(@RequestParam("account") String account,
                        @RequestParam("password") String password){
        SysUser loginUser = sysUserService.login(account, password);
        if(loginUser != null){
            // 登录成功，用户信息存入session
            session(Constants.SESSION_USER, loginUser);
            // 重定向到后台首页
            return redirect("/main/index");
        }else{
            throw new LoginException("登录失败，用户名或密码错误！");
        }
    }


    @GetMapping("/logout")
    public String logout(){
        session().invalidate();
        return redirect("/login");
    }

    // 跳转到后台首页
    @GetMapping("/main/index")
    public String index(){
        return "index";
    }

    // @ExceptionHandler(value = RuntimeException.class)
    public String handlerException(RuntimeException e, HttpServletRequest request) {
        // 设置捕获的错误对象到request作用域
        request.setAttribute(Constants.REQUEST_ERROR, e);
        // 跳转异常页面：/WEB-INF/jsp/500.jsp
        return "500";
    }

}
